<!--
 * @Author: 刘十三
 * @Date: 2024-02-23 10:22:59
 * @LastEditors: 刘十三
 * @LastEditTime: 2024-04-10 10:58:27
 * @FilePath: \NM-dev-1.3.1\dev\pages\internal\linkage\todo\arrangeTaskSet.vue
 * @Description: 内蒙多员联动 - 任务派发
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->

    <!-- 列表 -->
    <view class="content" v-if="show">
      <view class="header-list">
        <u-tabs :list="tabList" :show-bar="true" :is-scroll="false" :current="current" @change="handleChange" :bold="false"></u-tabs>
      </view>
      <u-divider bg-color="#f8f8f8" height="100" half-width="100%"></u-divider>
      <view class="content-main content-process" v-show="current == 0">
        <arrangeTaskInformation :is-edit="baseInfoEditFlag" :tdmId="tdmId" ref="arrangeTaskInformation" @isFieldsValue="fieldsValue" />
      </view>
      <view class="content-main content-process" v-show="current == 1">
        <arrangeTaskRetailerList :is-edit="baseInfoEditFlag" :tdmId="tdmId" :is-fields="isFields" ref="arrangeTaskRetailerList" />
      </view>
      <view class="content-main content-process" v-show="current == 2">
        <template v-if="checkInfoEditFlag == 'none'">
          <view class="u-padding-30">
            <flow-his-no-doc :bizUuid="tdmId" :processDefKey="processDefKey" />
          </view>
        </template>
        <template v-else>
          <arrangeTaskQuestion :is-edit="checkInfoEditFlag" ref="arrangeTaskQuestion" />
        </template>
      </view>
      <view class="content-main content-process" v-show="current == 3">
        <arrangeTaskResult :is-edit="checkInfoEditFlag" ref="arrangeTaskResult" v-if="checkInfoEditFlag != 'none'" />
      </view>
      <view class="content-main content-process" v-show="current == 4">
        <view class="u-padding-30">
          <flow-his-no-doc :bizUuid="tdmId" :processDefKey="processDefKey" v-if="checkInfoEditFlag != 'none'" />
        </view>
      </view>
      <!-- 按钮 (operateType)只判断新增-->
      <view class="submit-btns btn-other-cls" v-if="operateType == 'edit'">
        <u-row gutter="25" style="width: 100%;overflow-x: scroll; flex-wrap: nowrap;">
          <u-col span="6">
            <u-button @click="handleUpload">
              保存
            </u-button>
          </u-col>
          <u-col span="6">
            <u-button type="primary" @click="handleConfirm">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
      <view class="submit-btns btn-other-cls" v-if="step == 'onlySubmit'">
        <u-row gutter="25" style="width: 100%;overflow-x: scroll; flex-wrap: nowrap;">
          <u-col span="6" v-if="backFlag">
            <u-button type="error" @click="handleBack">
              退回
            </u-button>
          </u-col>
          <u-col :span="backFlag ? 6 : 12">
            <u-button type="primary" @click="handleConfirm">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
      <view class="submit-btns btn-other-cls" v-if="step == 'checkSubmit'">
        <u-row gutter="25" style="width: 100%;overflow-x: scroll; flex-wrap: nowrap;">
          <u-col span="6">
            <u-button @click="hanldeAddInformationEntry">
              发起我要办
            </u-button>
          </u-col>
          <u-col span="6">
            <u-button type="primary" @click="handleConfirm">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
    </view>

    <!-- 退回 -->
    <u-popup mode="bottom" height="41%" v-model="backShow" :safe-area-inset-bottom="true" :closeable="true">
      <view class="back-content">
        <view class="back-title" style="font-weight: bold;text-align: center; font-size:16px;">退回流程</view>
        <view class="back-form" v-if="backShow">
          <u-form class="u-form-m" :model="backForm" :error-type="['border-bottom']" label-width="auto" label-position="top" ref="bForm">
            <u-form-item label="退回意见" prop="approveMemo" :required="true">
              <view style="height: 100px;width: 100%">
                <u-input placeholder="请输入退回意见" v-model="backForm.approveMemo" type="textarea" :auto-height="false" maxlength="500" height="90"></u-input>
              </view>
            </u-form-item>
          </u-form>
          <u-button type="primary" @click="saveBackConfirm" style="margin-top: 15px">
            提交
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { uuid } from "@/common/util.js";
import linkageService from "@/service/internal/linkeage.service";
import FlowHisNoDoc from "@/components/flow-his-no-doc.vue";
import arrangeTaskInformation from "./components/arrangeTaskInformation.vue";
import arrangeTaskRetailerList from "./components/arrangeTaskRetailerList.vue";
import arrangeTaskQuestion from "./components/arrangeTaskQuestion.vue";
import arrangeTaskResult from "./components/arrangeTaskResult.vue";

export default {
  components: { arrangeTaskInformation, arrangeTaskRetailerList, arrangeTaskQuestion, arrangeTaskResult, FlowHisNoDoc },
  data() {
    return {
      current: 0,
      baseInfoEditFlag: "edit", // 基础信息编辑权限||view：查看；edit：编辑
      tabList: [
        {
          name: "任务信息",
        },
        {
          name: "零售户",
        },
      ],
      processDefKey: "task_distributed",
      show: false,
      backFlag: false,
      isFields: true, // 零售户信息是否必须提交
      tdmId: "", // 页面Id
      step: "view", // 按钮权限 || view 不显示；edit：显示
      checkInfoEditFlag: "none", // 核查问题及调查结果数据权限||none:不显示；view：查看；edit：编辑
      operateType: "view",
      backShow: false,
      backForm: {
        approveMemo: "",
      },
      rules: {
        approveMemo: [
          {
            required: true,
            message: "请输入退回意见",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  onLoad() {
    let param = this.getRouteParam();
    if (param.operateType == "approve") {
      this.baseInfoEditFlag = "edit";
      this.operateType = "edit";
    }
    if (param.bizUuid) {
      this.tdmId = param.bizUuid;
      this.getDetail(param.bizUuid);
    } else {
      this.tdmId = uuid();
      this.show = true;
    }
  },
  methods: {
    handleBack() {
      this.backShow = true;
      this.$nextTick(() => {
        this.$refs.bForm.setRules(this.rules);
      });
    },
    getDetail(tdmId) {
      let self = this;
      let params = {
        tdmId,
      };
      let urlParams = self.getRouteParam();
      self.$u.loading("数据加载中...");
      linkageService
        .getTaskDistributedMainInfo(params)
        .then((res) => {
          self.$u.hideLoading();
          if (res.success && res.code == 200) {
            // 是否可以退回
            self.backFlag = res.bean.backFlag;
            // 是否显示核查问题和调查结果
            self.checkInfoEditFlag = res.bean.checkInfoEditFlag;
            // 这里有传入的，也有请求的
            if (urlParams.operateType == "view") {
              self.baseInfoEditFlag = urlParams.operateType;
              self.step = urlParams.operateType;
            } else {
              self.baseInfoEditFlag = res.bean.baseInfoEditFlag;
              self.getCheckBaseInfoFlag(res.bean.tdmId, res.bean.transactOrgId);
              self.step = res.bean.step;
            }
            if (self.baseInfoEditFlag == "view") {
              self.isFields = false;
            }
            if (self.step == "checkSubmit") {
              self.current = 2;
            }

            if (self.checkInfoEditFlag == "none" && res.bean.processStatus != "01") {
              let array = [{ name: "审核意见" }];
              self.tabList = self.tabList.concat(array);
            }
            if (self.checkInfoEditFlag != "none") {
              let array = [{ name: "核查问题" }, { name: "调查结果" }, { name: "审核意见" }];
              self.tabList = self.tabList.concat(array);
            }
            // 显示页面
            self.show = true;
            // 判断选中的ticId
            let checkDistributedContentDtoList = [];
            let showCloumns = [];
            res.bean.taskDistributedContentVos.forEach((item) => {
              if (item.checkFlag == 1) {
                checkDistributedContentDtoList.push(item.ticId);
              }
              showCloumns.push({
                label: item.ticName,
                name: item.ticId,
                checked: item.checkFlag == 1, // 默认未选中
                assignTypeCode: item.assignTypeCode,
                assignTypeName: item.assignTypeName,
              });
            });
            self.$nextTick(() => {
              // 回显任务信息内容
              for (let key in self.$refs.arrangeTaskInformation.taskInfo) {
                self.$refs.arrangeTaskInformation.taskInfo[key] = res.bean[key];
                if (!self.$refs.arrangeTaskInformation.taskInfo.checkDistributedContentDtoList) {
                  self.$refs.arrangeTaskInformation.taskInfo.checkDistributedContentDtoList = checkDistributedContentDtoList.toString();
                }
              }

              // 组装 调查内容
              self.$refs.arrangeTaskInformation.showCloumns = showCloumns;
              self.$refs.arrangeTaskInformation.plannStatusName = res.bean.assignTypeName;
              self.$refs.arrangeTaskInformation.orgSelectName = res.bean.transactOrgName;

              // 回显零售户信息
              for (let keys in self.$refs.arrangeTaskRetailerList.retailer) {
                if (self.baseInfoEditFlag == "view") {
                  self.$refs.arrangeTaskRetailerList.retailer[keys] = res.bean[keys] || "/";
                } else {
                  self.$refs.arrangeTaskRetailerList.retailer[keys];
                }
              }

              // 组装核查问题
              let questionList = res.bean.taskDistributedIssueVos.map((item) => {
                return {
                  ...item,
                  resultValue: item.resultValue ? item.resultValue : "",
                };
              });
              if (self.$refs.arrangeTaskQuestion) {
                self.$refs.arrangeTaskQuestion.taskDistributedIssueVos = questionList;
                self.$refs.arrangeTaskQuestion.question.openDoorFlag = res.bean.openDoorFlag;
              }

              // 回显调查结果
              if (self.$refs.arrangeTaskResult) {
                for (let V in self.$refs.arrangeTaskResult.result) {
                  self.$refs.arrangeTaskResult.result[V] = res.bean[V];
                  self.$refs.arrangeTaskResult.result.checkFileId = res.bean.checkFileId ? res.bean.checkFileId : uuid();
                }
                self.$refs.arrangeTaskResult.getFileList();
              }
            });
          }
        })
        .catch((err) => {
          self.$u.hideLoading();
        });
    },
    // 退回
    saveBackConfirm() {
      let self = this;
      self.$refs.bForm.validate((valid) => {
        if (valid) {
          self.$modal.showLoading("数据加载中...");
          let param = {
            tdmId: self.tdmId,
            approveMemo: self.backForm.approveMemo,
          };
          linkageService
            .backToCheck(param)
            .then((rs) => {
              self.$modal.hideLoading();
              if (rs.success) {
                self.$u.toast("流程已退回");
                self.back();
              } else {
                self.$u.toast(rs.msg);
              }
            })
            .catch((err) => {
              self.$modal.hideLoading();
            });
        }
      });
    },
    getCheckBaseInfoFlag(tdmId, transactOrgId) {
      let self = this;
      let params = {
        tdmId,
        transactOrgId,
      };
      self.$u.loading("数据加载中...");
      linkageService
        .getCheckBaseInfoFlag(params)
        .then((res) => {
          self.$u.hideLoading();
          if (res.success && res.code == 200) {
            self.isFields = res.bean;
            self.$refs.arrangeTaskRetailerList.required = res.bean;
            self.$refs.arrangeTaskRetailerList.rules.checkDistributedContentDtoList[0].required = res.bean;
          }
        })
        .catch((err) => {
          self.$u.hideLoading();
        });
    },
    handleChange(index) {
      this.current = index;
    },
    fieldsValue(value) {
      this.isFields = value;
      this.$refs.arrangeTaskRetailerList.$refs.uForm.setRules(value ? this.$refs.arrangeTaskRetailerList.rules : {});
    },
    handleConfirm() {
      let form = {};
      let self = this;
      let a = self.$refs.arrangeTaskInformation ? self.$refs.arrangeTaskInformation.checkForm() : {};
      let b = self.$refs.arrangeTaskRetailerList ? self.$refs.arrangeTaskRetailerList.checkForm() : {};
      let c = self.$refs.arrangeTaskQuestion ? self.$refs.arrangeTaskQuestion.checkForm() : {};
      let d = self.$refs.arrangeTaskResult ? self.$refs.arrangeTaskResult.checkForm() : {};
      Promise.all([a, b, c, d])
        .then((result) => {
          result.forEach((item) => {
            Object.assign(form, item);
          });
          const date1 = new Date(form.arrangeDate); // 任务安排日期;
          const date2 = new Date(form.planFinishDate); // 任务计划完成日期
          if (date1 > date2) {
            self.current = 0;
            self.$u.toast("任务安排日期不能大于任务计划完成日期");
            return;
          }
          // 当零售户信息校验时候，如果未传直接跳转至对应的tab页
          if (self.isFields) {
            if (!form.licNo) {
              self.current = 1;
              self.$refs.arrangeTaskRetailerList.$refs.uForm.setRules(self.$refs.arrangeTaskRetailerList.rules);
              return;
            }
          }
          self.submitForm = form;
          let params = {
            tdmId: self.submitForm.tdmId,
            transactOrgId: self.submitForm.transactOrgId,
          };
          linkageService
            .submitSelectPersonFlag(params)
            .then((res) => {
              if (res.success && res.code == 200) {
                if (res.bean) {
                  self.chooseNextHandlePersonsId();
                } else {
                  self.handleSubmit();
                }
              }
            })
            .catch((err) => {
              self.$u.toast("选择审批人失败");
            });
        })
        .catch((err) => {
          this.current = err || 0;
        });
    },
    handleSubmit() {
      let self = this;
      self.$u.loading("数据加载中...");
      linkageService
        .submitTaskDistributedMain(self.submitForm)
        .then((res) => {
          self.$u.hideLoading();
          if (res.success && res.code == 200) {
            this.$u.toast("提交成功");
            self.back();
          } else {
            this.$u.toast(res.msg);
          }
        })
        .catch((err) => {
          self.$u.hideLoading();
        });
    },
    back() {
      this.backPrev({
        paramKey: "refresh",
        param: true,
      });
    },
    // 选择下一节审批人
    chooseNextHandlePersonsId() {
      let self = this;
      self.$u.route({
        url: "/pages/internal/linkage/components/flowUserList",
        params: {
          status: "4",
          gfCode: self.processDefKey,
          tdmId: self.submitForm.tdmId,
          transactOrgId: self.submitForm.transactOrgId,
        },
      });
    },
    updateBackState(param) {
      if (param.retailerSelectBack) {
        this.$nextTick(() => {
          this.$refs.arrangeTaskRetailerList.retailer.licNo = param.retailerSelectBack.licNo;
          this.$refs.arrangeTaskRetailerList.retailer.companyName = param.retailerSelectBack.companyName;
          this.$refs.arrangeTaskRetailerList.retailer.managerName = param.retailerSelectBack.managerName;
          this.$refs.arrangeTaskRetailerList.retailer.retailTel = param.retailerSelectBack.retailTel;
          this.$refs.arrangeTaskRetailerList.retailer.businessAddr = param.retailerSelectBack.businessAddr;
          this.$refs.arrangeTaskRetailerList.retailer.issueOrgCode = param.retailerSelectBack.issueOrgCode;
          this.$refs.arrangeTaskRetailerList.retailer.issueOrgName = param.retailerSelectBack.issueOrgName;
          this.$refs.arrangeTaskRetailerList.retailer.issueOrgUuid = param.retailerSelectBack.orgUuid;
        });
      }
      if (param.flowUserSelectBack) {
        this.submitForm.nextPersonUuid = param.flowUserSelectBack;
        this.handleSubmit();
      }
    },
    // 发起我要办
    hanldeAddInformationEntry() {
      let self = this;
      this.$u.route({
        url: "/pages/internal/linkage/todo/informationEntryAddUpdate",
        type: "to",
        params: {
          isStatus: 0, // 0 新增 1编辑 2查看
          operateType: "approve",
          tdmId: self.tdmId,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 0;
}
.content {
  overflow: hidden;
  .header-list {
    position: fixed;
    background: white;
    padding: 0rpx 24rpx;
    /* #ifdef H5-ONLY  */

    top: 44px;
    /* #endif */
    /* #ifndef H5-ONLY  */
    top: 0px;
    /* #endif */
    left: 0px;
    width: 100%;
    z-index: 999;
    box-sizing: border-box;
  }
  .content-main {
    padding: 0rpx 25rpx 0rpx;
    margin-bottom: 100px;
  }
}
.back-content {
  padding: 30rpx 50rpx;
  height: 100%;
  overflow: hidden;
}
/deep/ .back-form {
  .u-input__textarea {
    height: 100px;
  }
}
</style>
